import './js/moxie.js';
import './js/plupload.dev.js';
import { getosssignForPost } from './workdatadoc.config';
import { vendorsDanger } from 'utils/config.js';

let expiresTime = 0;
let aliyunoss = {};
let ossconfig = {
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'browse',
    url: '',
    multi_selection: false,
    // multipart:true,
    multipart_params: {},
    // filters: {
    //     mime_types : [ //只允许上传图片和zip,rar文件
    //     { title : "Image files", extensions : "jpg,gif,png,bmp" }, 
    //     { title : "Zip files", extensions : "zip,rar" },
    //     { title : "excel files", extensions : "xls,xlsx" },
    //     { title : "word files", extensions : "doc,docx" }
    //     ],
    //     max_file_size : '10mb', //最大只能上传10mb的文件
    //     prevent_duplicates : true //不允许选取重复文件
    // },
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}


export function selectFile(record) {
    this.filepointer = record;
    document.getElementById('selectfile').click();
}

export function handleSelectFile(page) {
    let ele = document.getElementById('selectfile');

    if (ele.files.length > 0) {
        let record = this.filepointer;
        record.contentVOS = record.contentVOS || [];
        // if (record.contentVOS.length > 0) {
        //     record.contentVOS[record.contentVOS.length - 1].valid = false;
        // }
        for (let i = 0, len = ele.files.length; i < len; i++) {
            let suffixtest = /(doc|docx|xls|xlsx|pdf)$/i;
            if (ele.files[i].size / 1024 / 1024 > 5 || !suffixtest.test(ele.files[i].name)) {
                vendorsDanger({ text: "只能上传word、excel和pdf文件,最大5MB。" });
                continue;
            }

            let fileitem = { sname: ele.files[i].name, percent: 0, valid: true };
            record.contentVOS.push(fileitem);
            record.selectfile = true;
            record.datumType = 1;

            if (new Date().getTime() + 10000 >= expiresTime * 1000) {
                getosssignForPost({ ieStamp: new Date().getTime(), isAjax: 1 }).then((res) => {
                    let data = res.data;
                    if (data.resultCode == "ok") {
                        aliyunoss = data.result;
                        expiresTime = aliyunoss.expire;

                        uploaderFactory.bind(this)(ele.files[i], fileitem);
                    }
                });
            } else {
                uploaderFactory.bind(this)(ele.files[i], fileitem);
            }
        }

        this.forceUpdate();
    }
}

function uploaderFactory(file, fileitem) {
    ossconfig.url = aliyunoss.host;

    let filename = file.name;
    let key = aliyunoss.dir + 'collate' + guid() + '/' + filename;
    ossconfig.multipart_params = {
        'key': key,
        'policy': aliyunoss.policy,
        'OSSAccessKeyId': aliyunoss.accessKeyId,
        'signature': aliyunoss.signature,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        //'callback' : callbackbody,
    }

    let _self = this;
    let fileuploader = new plupload.Uploader(ossconfig);

    fileuploader.bind('UploadProgress', function (uploader, file) {
        // console.log('UploadProgress');
        // console.log(file.percent);
        fileitem.percent = file.percent;
        if(fileitem.percent>=100){
            fileitem.ossName = key;
        }
        _self.forceUpdate();
    });

    fileuploader.bind('FilesAdded', function (uploader, files) {
        // console.log('FilesAdded');
    });

    fileuploader.bind('FileUploaded', function (uploader, file, responseObject) {
        // console.log('FileUploaded');
        fileitem.ossName = key;
        // console.log(responseObject);
    });

    fileuploader.bind('UploadComplete', function (uploader, files) {
        // console.log('UploadComplete');
        uploader.destroy();
    });

    fileuploader.bind('PostInit', function (fileuploader) {
        // console.log('PostInit');
        fileuploader.addFile(file);
        fileuploader.start();
    });

    fileuploader.init();

}